package com.boot.base.common.utils;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;

import java.text.SimpleDateFormat;
import java.util.Date;

public abstract class JsonUtil {
    public static <T> T jsonToObject(String sourceAsString, Class<T> c) {
        return (T) JSONObject.toBean(JSONObject.fromObject(sourceAsString), c);
    }

    public static byte[] objectToJson(Object data) {
        JsonConfig config = new JsonConfig();
        config.registerJsonValueProcessor(Date.class, new JsonValueProcessor() {
            @Override
            public Object processArrayValue(Object o, JsonConfig jsonConfig) {
                return process(o);
            }

            @Override
            public Object processObjectValue(String s, Object o, JsonConfig jsonConfig) {
                return process(o);
            }

            private Object process(Object value) {
                if (value == null) {
                    return "";
                } else {
                    return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((Date) value);
                }
            }
        });
        return JSONObject.fromObject(data,config).toString().getBytes();
    }

    public static String objToJson(Object data ) {
        return JSONObject.fromObject(data).toString();
    }
    }
